package zzps.exeed.kernel.config;

import zzps.exeed.kernel.ExeedApp;

import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.util.Map;
import java.util.Properties;
import java.util.concurrent.ConcurrentHashMap;

public class Config {
    private ClassLoader classLoader;
    private Map<String,ConfigValue> config = new ConcurrentHashMap<>(2048);

    public Config(ClassLoader classLoader) {
        this.classLoader = classLoader;
    }

    public void load(ExeedApp exeedApp, String[] args){
        //1，加载app配置
        fromApp();
        //2，加载系统配置
        fromSystem();
        //3，加载启动配置
        fromCommand(args);
    }

    public Object get(String name){
        ConfigValue configValue = config.get(name);
        if (configValue == null){
            return null;
        }
        return configValue.getValue();
    }
    public void add(String name,Object value){
        ConfigValue configValue = new ConfigValue(value, ConfigFrom.APP);
        config.put(name,configValue);
    }


    //从app.properties加载配置
    private void fromApp(){
        URL resource = classLoader.getResource("app.properties");
        if (resource != null){
            Properties properties = new Properties();
            try (InputStream inputStream = resource.openStream()){
                properties.load(inputStream);
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
            add(properties,ConfigFrom.APP);
        }
    }
    //从系统属性加载配置
    private void fromSystem() {
        Properties properties = System.getProperties();
        add(properties,ConfigFrom.SYSTEM);
    }
    //从启动参数加载配置
    private void fromCommand(String[] args){
        for (String arg : args) {
            int index = arg.indexOf('=');
            if (index >0){
                String name = arg.substring(0, index);
                String value = arg.substring(index + 1);
                ConfigValue configValue = new ConfigValue(value, ConfigFrom.BOOT);
                config.put(name, configValue);
            }
        }
    }
    private void add(Properties properties,ConfigFrom configFrom){
        for (Map.Entry<Object, Object> entry : properties.entrySet()) {
            Object value = entry.getValue();
            if (value instanceof String) {
                String s = (String) value;
                if (s.isEmpty()) {
                    continue;
                }
            }
            ConfigValue configValue = new ConfigValue(value, configFrom);
            config.put(entry.getKey().toString(), configValue);
        }
    }
}
